package com.portal.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.portal.common.Result;
import com.portal.entity.News;
import com.portal.entity.NewsCategory;
import com.portal.service.NewsCategoryService;
import com.portal.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻控制器
 */
@RestController
@RequestMapping("/news")
@CrossOrigin
public class NewsController {
    
    @Autowired
    private NewsService newsService;
    
    @Autowired
    private NewsCategoryService categoryService;
    
    /**
     * 获取新闻分类列表
     */
    @GetMapping("/categories")
    public Result<List<NewsCategory>> getCategories() {
        try {
            List<NewsCategory> categories = categoryService.getEnabledCategories();
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取新闻分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取新闻列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getNewsList(
            @RequestParam(required = false) Long categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            Map<String, Object> result = newsService.getNewsList(categoryId, page, size, keyword);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取新闻列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取新闻详情
     */
    @GetMapping("/{id}")
    public Result<News> getNewsDetail(@PathVariable Long id) {
        try {
            News news = newsService.getNewsDetail(id);
            if (news != null) {
                return Result.success(news);
            } else {
                return Result.error("新闻不存在");
            }
        } catch (Exception e) {
            return Result.error("获取新闻详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取新闻的上一篇和下一篇
     */
    @GetMapping("/{id}/adjacent")
    public Result<Map<String, News>> getAdjacentNews(@PathVariable Long id) {
        try {
            Map<String, News> adjacentNews = newsService.getAdjacentNews(id);
            return Result.success(adjacentNews);
        } catch (Exception e) {
            return Result.error("获取相邻新闻失败：" + e.getMessage());
        }
    }

    /**
     * 获取最新新闻
     */
    @GetMapping("/latest")
    public Result<List<News>> getLatestNews(@RequestParam(defaultValue = "6") Integer limit) {
        try {
            List<News> newsList = newsService.getLatestNews(limit);
            return Result.success(newsList);
        } catch (Exception e) {
            return Result.error("获取最新新闻失败：" + e.getMessage());
        }
    }
} 